<?php
/**
 * Created by PhpStorm.
 * User: peter
 * Date: 2018/12/7
 * Time: 2:13 PM
 */

namespace app\admin\controller;


use app\model\Member;
use think\Request;

class Bill extends Auth
{
    /**
     * @purpose 获取账单列表
     * @param Request $request
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function items (Request $request)
    {
        $page = $request->get('page', 1);
        $size = $request->get('size', 20);
        $start = $request->get('start', '');
        $end = $request->get('end', '');
        $type = $request->get('type', 0);
        $searchType = (int) $request->get('searchType', 0);
        $searchValue = $request->get('searchValue');
        $where = [];
        $uid = [];
        if ($searchType) {
            $memberWhere = [];
            switch ($searchType) {
                case 1: // 用户名
                    $memberWhere[] = ['username', ['like', '%'.$searchValue], ['like', '%'.$searchValue.'%'], ['like', $searchValue.'%'], 'or'];
                    break;
                case 2: // 用户昵称
                    $memberWhere[] = ['nickname', ['like', '%'.$searchValue], ['like', '%'.$searchValue.'%'], ['like', $searchValue.'%'], 'or'];
                    break;
                case 3: // 用户手机号码
                    $memberWhere[] = ['mobile', '=', $searchValue];
                    break;
                case 4: // 用户手机号码
                    $where[] = ['descriptions', ['like', '%'.$searchValue],['like', '%'.$searchValue.'%'], ['like', $searchValue.'%'], 'or'];
                    break;
            }
            $memberInfo = Member::M()
                ->where($memberWhere)
                ->field('uid')
                ->select();
            foreach ($memberInfo as $item) {
                array_push($uid, $item->uid);
            }
            $where[] = ['uid', 'in', $uid];
        }
        if ($start && $end) {
            $where[] = ['create_at', '>', strtotime($start)];
            $where[] = ['create_at', '<', strtotime($end)];
        }
        if ($type) {
            $where[] = ['type', '=', $type];
        }
        $total      = \app\model\Bill::M()
            ->where($where)
            ->count(1);
        $list       = \app\model\Bill::M()
            ->with(['member' => function($query) {
                $query->field('uid,username,nickname,mobile');
            }])
            ->where($where)
            ->field('id,uid,type,order_no,quota,pay_method,descriptions,FROM_UNIXTIME(create_at, "%Y-%m-%d %H:%i:%s") as create_date')
            ->order('create_at desc')
            ->page($page, $size)
            ->select();
        return $this->response([
           'total' => $total,
           'list' => $list
        ]);
    }
}